//
//  BCWaitDetailVC.m
//  BangcaiDriver
//
//  Created by lsy on 16/8/22.
//  Copyright © 2016年 BC. All rights reserved.
//

#import "BCWaitDetailVC.h"
#import "BCWaitDetailHeaderCollectionViewCell.h"
#import "BCWaitDetailCollectionViewCell.h"

@interface BCWaitDetailVC () <UICollectionViewDelegate,UICollectionViewDataSource>
//主视图
@property (nonatomic, strong) UICollectionView *mainCollectionView;
@property (nonatomic,weak) dispatch_source_t mTimer;
@end

@implementation BCWaitDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self p_initNavgationBar];
    [self p_initCollectionView];
    [self p_initUnderBar];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //隐藏导航栏
    self.navigationController.navigationBar.hidden = NO;
    if (!self.rdv_tabBarController.tabBarHidden) {
        [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    if (self.rdv_tabBarController.tabBarHidden) {
        [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - View init
-(void)p_initNavgationBar {
    self.title = @"订单详情";
    self.view.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:1.000];
    UIImage *rightBarItemImage = [UIImage imageNamed:@"接单"];
    UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBarButton setBackgroundImage:rightBarItemImage forState:UIControlStateNormal];
    [rightBarButton setTitle:@"我要接单" forState:UIControlStateNormal];
    rightBarButton.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    rightBarButton.frame = CGRectMake(0, 0, 72, 22);
    [rightBarButton addTarget:self action:@selector(rightItemAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarButton];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"查看地图" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemAction:)];
}

-(void)p_initUnderBar {
    //52
    CGFloat height = 52.f;
    CGFloat offset = self.navigationController.navigationBar.frame.size.height+20.f;
    UIButton *u_Left_Button = [UIButton buttonWithType:UIButtonTypeCustom];
    u_Left_Button.frame = CGRectMake(0, SCREEN_HEIGHT-height-offset, SCREEN_WIDTH/2, height);
    [u_Left_Button setBackgroundColor:[UIColor whiteColor]];
    [u_Left_Button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [u_Left_Button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [u_Left_Button setTitle:@"放弃" forState:UIControlStateNormal];
    [u_Left_Button addTarget:self action:@selector(underLeftAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:u_Left_Button];
    UIButton *u_Right_Button = [UIButton buttonWithType:UIButtonTypeCustom];
    u_Right_Button.frame = CGRectMake(u_Left_Button.frame.size.width, SCREEN_HEIGHT-height-offset, SCREEN_WIDTH/2, height);
    [u_Right_Button setBackgroundColor:BangcaiOrange];
    [u_Right_Button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [u_Right_Button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    
    __block int timeout=180; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"接单超时"
                                                                               message:@""
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定"
                                                                        style:UIAlertActionStyleDefault
                                                                      handler:^(UIAlertAction * action) {
                                                                          [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"接单（%d秒）", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [u_Right_Button setTitle:strTime forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    _mTimer = _timer;
    dispatch_resume(_timer);
    
    [u_Right_Button addTarget:self action:@selector(underRightAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:u_Right_Button];
}

- (void)p_initCollectionView {
    UICollectionViewFlowLayout *flowLayout= [[UICollectionViewFlowLayout alloc]init];
    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 3, SCREEN_WIDTH, SCREEN_HEIGHT-3-52-65) collectionViewLayout:flowLayout];
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    //设置contentInset属性（上左下右的值）
    self.mainCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 114.f, 0);
    self.mainCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mainCollectionView];
}

#pragma mark - Private Action
- (void)rightItemAction:(UIButton *)item {
    NSLog(@"right item clicked");
}

- (void)underLeftAction:(UIButton *)item {
    NSLog(@"under left item clicked");
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"确定放弃此单？"
                                                                   message:@""
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self.navigationController popViewControllerAnimated:YES];
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                            style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                          }];
    
    [alert addAction:cancelAction];
    [alert addAction:defaultAction]; 
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)underRightAction:(UIButton *)item {
    NSLog(@"under right item clicked");
    dispatch_source_cancel(_mTimer);
    dispatch_async(dispatch_get_main_queue(), ^{
        //设置界面的按钮显示 根据自己需求设置
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"接单成功"
                                                                       message:@""
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定"
                                                                style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  [self.navigationController popViewControllerAnimated:YES];
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    });
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    else {
        return 6;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        static NSString *ID = @"WaitDetailHeaderCellIdentifer";
        BCWaitDetailHeaderCollectionViewCell *cell = [BCWaitDetailHeaderCollectionViewCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        return cell;
    }
    else {
        static NSString *ID = @"WaitDetailCellIdentifer";
        BCWaitDetailCollectionViewCell *cell = [BCWaitDetailCollectionViewCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.upLine.hidden = YES;
        }
        else if (indexPath.row == (6-1)) { //条数
            cell.downLine.hidden = YES;
        }
        return cell;
    }
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{
    UIEdgeInsets top = {0,0,0,0};
    return top;
}

//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return CGSizeMake(self.view.frame.size.width, SCREEN_HEIGHT*0.2f);
    }
    else {
        return CGSizeMake(self.view.frame.size.width, 65.f);
    }
}

//每个item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

//每个section中不同的行之间的行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0;
}

//collectionview点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

@end
